package com.hy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/qian/*",filterName = "LoginFilter")
public class CodeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CodeFilter========>");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String uri = request.getRequestURI();
        if(uri.endsWith("login.jsp") ||uri.endsWith(".js")||uri.endsWith(".png")){
            filterChain.doFilter(request,response);
            return;
        }else if (uri.endsWith("user")) {
            String ac = request.getParameter("ac");
            if("toHomePage".equals(ac) || "registerReview".equals(ac) || "register".equals(ac) ){
                filterChain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = request.getSession(true);
        if(session != null){
            Object username = session.getAttribute("username");
            System.out.println("cideFilter======>"+username);
            if(username == null){
                response.sendRedirect("/demo05/login.jsp");
                return;
            }
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
